package com.cn.kabalifemerchants.ui.order.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cn.kabalifemerchants.R;
import com.cn.kabalifemerchants.base.LazyFragment;
import com.cn.kabalifemerchants.config.CustomRefreshListener;
import com.cn.kabalifemerchants.config.LoginHelper;
import com.cn.kabalifemerchants.config.RefreshHelper;
import com.cn.kabalifemerchants.ui.login.bean.MsgBean;
import com.cn.kabalifemerchants.ui.order.activity.ServiceOrderDetailsActivity;
import com.cn.kabalifemerchants.ui.order.adapter.OrderAdapter;
import com.cn.kabalifemerchants.ui.order.bean.OrderListListBean;
import com.cn.kabalifemerchants.utils.RxToast;
import com.cn.kabalifemerchants.view.dialogView.ApplyShopDialog;
import com.kongzue.dialog.v2.SelectDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by 晓林 on 2020/10/20.
 * function:
 */
public class OrderListFragments extends LazyFragment<OrderListView, OrderListPresenter> implements OrderListView {


    @BindView(R.id.rv_notice)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private View notDataView;
    List<OrderListListBean.ResultBean.DataBean> mList;
    OrderAdapter mAdapter;
    private int mId;
    ApplyShopDialog applyShopDialog;

    int itemPosition = -1;

    public static OrderListFragments getInstance(int mid) {
        OrderListFragments fragment = new OrderListFragments();
        fragment.mId = mid;
        return fragment;
    }

    @Override
    protected OrderListPresenter createPresenter() {
        return new OrderListPresenter();
    }

    @Override
    protected void onUserVisible() {
        pagehttp = 1;
        getListData();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.recyclerview_refresh;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        ButterKnife.bind(this, view);
        mList = new ArrayList<>();
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(getMe());
        layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager3.setSmoothScrollbarEnabled(true);
        layoutManager3.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(layoutManager3);
        recyclerView.setNestedScrollingEnabled(false);
        //创建适配器
        mAdapter = new OrderAdapter(R.layout.fragment_order_mall_item, mList, mId);
        //给RecyclerView设置适配器
        recyclerView.setAdapter(mAdapter);
        notDataView = getLayoutInflater().inflate(R.layout.show_empty_view, (ViewGroup) recyclerView.getParent(), false);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshLayout.autoRefresh();
            }
        });

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("sign", mId);
                bundle.putInt("id", mAdapter.getItem(position).getId());
                $startActivity(ServiceOrderDetailsActivity.class, bundle);
            }
        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {


                    case R.id.tv_btn_jiedan:
                        SelectDialog.show(getMe(), "提示", "确定要接该订单吗？", "确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                itemPosition = position;

                                mPresenter.onOrderUpData(LoginHelper.getLonginData().getResult(), mAdapter.getItem(position).getId(), 3);
                            }
                        }, "取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });break;

                    case R.id.tv_btn_tongyi:
                        SelectDialog.show(getMe(), "提示", "确定同意退款吗？", "确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                itemPosition = position;

                                mPresenter.onOrderUpTuiData(LoginHelper.getLonginData().getResult(), mAdapter.getItem(position).getId(), 1);
                            }
                        }, "取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });break;
                    case R.id.tv_btn_jujue:
                        //todo 接單
                        SelectDialog.show(getMe(), "提示", "确定拒绝退款吗？", "确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                itemPosition = position;

                                mPresenter.onOrderUpTuiData(LoginHelper.getLonginData().getResult(), mAdapter.getItem(position).getId(), 2);
                            }
                        }, "取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });break;
                    case R.id.tv_btn_weikuan:
                        //todo 尾款
                        if (applyShopDialog == null)
                            applyShopDialog = new ApplyShopDialog(getMe());
                        applyShopDialog.getTv_btn_next().setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (!TextUtils.isEmpty(applyShopDialog.getEt_name().getText().toString().trim())) {
                                    Double money = Double.parseDouble(applyShopDialog.getEt_name().getText().toString().trim());
                                    if (money > 0) {
                                        itemPosition = position;
                                        hintPopInput(applyShopDialog.getEt_name());
                                        mPresenter.onOrderUpData(LoginHelper.getLonginData().getResult(), mAdapter.getItem(position).getId(), applyShopDialog.getEt_name().getText().toString().trim());
                                    } else RxToast.error("尾款比如大于0");
                                } else RxToast.error("请输入尾款");
                            }
                        });
                        applyShopDialog.show();
                        break;
                    case R.id.tv_btn_quxiao:
                        //todo 取消
                        SelectDialog.show(getMe(), "提示", "确定要取消并退款该订单吗？", "确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                itemPosition = position;
                                mPresenter.onOrderUpData(LoginHelper.getLonginData().getResult(), mAdapter.getItem(position).getId());
                            }
                        }, "取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        break;
                    case R.id.ll_btn_phone:
                        if (!TextUtils.isEmpty(mAdapter.getItem(position).getPhone())) {
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            Uri data = Uri.parse("tel:" + mAdapter.getItem(position).getPhone());
                            intent.setData(data);
                            startActivity(intent);
                        }
                        break;
                }
            }
        });
        initRefreshLayout();

//
//        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean.class)
//                .compose(new SchedulerTransformer<RxBusBean>())
//                .subscribe(new Action1<RxBusBean>() {
//                    @SuppressLint("WrongConstant")
//                    @Override
//                    public void call(RxBusBean rxBusBean) {
//                        if (rxBusBean.getSign() == 1111 && rxBusBean.getId() == 1111) {
//                            //详情操作成功以后。
//                            pagehttp = 1;
//                            getListData();
//                        } else if (rxBusBean.getId() == 2002 && rxBusBean.getSign() == 2002) {
//                            RxToast.success("支付成功");
//                            Constants.PAY_SIGN = 0;
//                            refreshLayout.autoRefresh();
//                        }
//                    }
//                });


    }

    /**
     * 刷新
     */
    public void initRefreshLayout() {
        RefreshHelper.initRefreshLayout(refreshLayout, new CustomRefreshListener() {
            @Override
            public void _onRefresh(RefreshLayout refreshLayout) {
                pagehttp = 1;
                getListData();
            }

            @Override
            public void _onLoadMore(RefreshLayout refreshLayout) {
                pagehttp++;
                if (null != mList) {
                    getListData();
                }
            }
        });
    }

    private void getListData() {
        if (mId == 0)
            mPresenter.onOrderGoodsListData(LoginHelper.getLonginData().getResult(), 8, pagehttp, pageNum);
        else if (mId == 1)
            mPresenter.onOrderGoodsListData(LoginHelper.getLonginData().getResult(), 9, pagehttp, pageNum);
        else if (mId == 2)
            mPresenter.onOrderGoodsListData(LoginHelper.getLonginData().getResult(), 10, pagehttp, pageNum);
        else if (mId == 3)
            mPresenter.onOrderGoodsListData(LoginHelper.getLonginData().getResult(), 11, pagehttp, pageNum);
        else if (mId == 4)
            mPresenter.onOrderGoodsListData(LoginHelper.getLonginData().getResult(), 12, pagehttp, pageNum);
    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RefreshHelper.finishRefresh(refreshLayout, pagehttp);
        RxToast.error(msg);

    }

    @Override
    public Context _getContext() {
        return null;
    }

    @Override
    public void onOrderListSuccess(OrderListListBean bean) {
        RefreshHelper.finishRefresh(refreshLayout, pagehttp);
        if (pagehttp == 1) {
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.replaceData(bean.getResult().getData());
            } else {
                mAdapter.replaceData(bean.getResult().getData());
                mAdapter.setEmptyView(notDataView);
            }
        } else {
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.addData(bean.getResult().getData());
            }

        }
    }

    @Override
    public void onOrderUpSuccess(MsgBean bean) {
        RxToast.success(bean.getResult());
        if (applyShopDialog != null) {
            applyShopDialog.dismiss();
            applyShopDialog.getEt_name().setText("");
        }
        if (itemPosition > -1) {
            mAdapter.remove(itemPosition);
            itemPosition = -1;
            mAdapter.notifyDataSetChanged();
            if (mAdapter.getData().size() == 0)
                mAdapter.setEmptyView(notDataView);
        }
    }

    @Override
    public void onOrderUpTuiSuccess(MsgBean bean) {
        RxToast.success(bean.getMsg());
        refreshLayout.autoRefresh();
    }

    /**
     * pw消失隐藏软键盘
     *
     * @param view
     */
    public void hintPopInput(View view) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 2);
        }
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}
